package com.ruoyi.web.controller.system;

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.htmlconverter.qt.Size;

import java.awt.*;
import java.awt.geom.*;


public class insertTiledTextWatermark {
    public static void main(String[] args) {

        //创建PdfDocument类的对象
        PdfDocument pdf = new PdfDocument();

        //载入PDF文件
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\应急广播new\\2023年红谷滩区应急广播系统建设项目验收资料需用印扫描版20231229.pdf");

        //循环遍历PDF文档中的所有页面以逐个添加水印
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.BOLD, 20));

        for (int i = 0; i < pdf.getPages().getCount(); i++){
            PdfPageBase pageBase = pdf.getPages().get(i);
            insertTextWatermark(pageBase, font, "2023年红谷滩区应急广播系统建设项目验收资料", 1, 1);
        }

        //保存文档
        pdf.saveToFile("C:\\Users\\Administrator\\Desktop\\应急广播new\\result1.pdf");
    }

    static void insertTextWatermark(PdfPageBase page, PdfTrueTypeFont font, String watermark, int row, int column) {

        //计算两个偏移变量的值以用于计算坐标的平移量
        float set1 = (float)(font.measureString(watermark).getWidth() * Math.sqrt(2)/4);
        float set2 = (float)(font.measureString(watermark).getHeight() * Math.sqrt(2)/4);

        //创建一个平铺笔刷
        PdfTilingBrush brush = new PdfTilingBrush(new Dimension((int) (page.getActualSize().getWidth()/column), (int) (page.getActualSize().getHeight()/row)));
        brush.getGraphics().setTransparency(0.3f);
        brush.getGraphics().save();
        brush.getGraphics().translateTransform(brush.getSize().getWidth()/2 - set1 - set2, brush.getSize().getHeight()/2 + set1 - set2);
        brush.getGraphics().rotateTransform(-45);

        //绘制水印文本到平铺笔刷
        brush.getGraphics().drawString(watermark, font, PdfBrushes.getBlack(), 0, 0);
        brush.getGraphics().restore();

        //使用该平铺笔刷绘制水印
        page.getCanvas().drawRectangle(brush, new Rectangle(new Point(0, 0), new Dimension((int)(page.getActualSize().getWidth()), (int)(page.getActualSize().getHeight()))));
    }
}